package com.zhijian.medical.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.NgsHszbqMapper;
import com.zhijian.medical.entity.dto.SangerSjpzqPcrDto;
import com.zhijian.medical.entity.po.ExperimentProcessSample;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Ngs;
import com.zhijian.medical.entity.po.NgsHszbq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleUpdateVo;
import com.zhijian.medical.entity.vo.request.NgsHszbqSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.NgsHszbqSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleNgsOrSangerVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.NgsHszbqVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.NgsStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.NgsHszbqService;
import com.zhijian.medical.service.NgsService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 二代测序-核酸制备区 业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-23 14:59:37
 */
@Slf4j
@Service
public class NgsHszbqServiceImpl implements NgsHszbqService {

    @Autowired
    private NgsHszbqMapper mapper;

    @Autowired
    private NgsService ngsService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public NgsHszbq selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public NgsHszbq selectByNgsId(Long ngsId) {
        return mapper.selectByNgsId(ngsId);
    }

    @Override
    public NgsHszbqVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public NgsHszbqVo selectVoByNgsId(Long ngsId) {
        NgsHszbqVo ngsHszbqVo = mapper.selectVoByNgsId(ngsId);
        if (Objects.isNull(ngsHszbqVo)) {
            return null;
        }
        Ngs ngs = ngsService.selectById(ngsId);
        if (Objects.isNull(ngs)) {
            return null;
        }
        ngsHszbqVo.setResult(ngs.getStatus() > NgsStatusEnum.HSZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        ngsHszbqVo.setResultStr(ngs.getStatus() > NgsStatusEnum.HSZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String pdhfyybData = ngsHszbqVo.getPdhfyybData();
        if (StringUtils.isNotBlank(pdhfyybData)) {
            ngsHszbqVo.setPdhfyybDataList(JsonUtil.toArray(pdhfyybData, SangerSjpzqPcrDto.class));
        }
        //准备数据
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .experimentProcessId(ngsId)
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(experimentProcessSampleVos)) {
            ngsHszbqVo.setNgsReadyList(experimentProcessSampleVos.stream().map(e -> {
                ExperimentProcessSampleNgsOrSangerVo experimentProcessSampleNgsOrSangerVo = new ExperimentProcessSampleNgsOrSangerVo();
                BeanUtils.copyProperties(e, experimentProcessSampleNgsOrSangerVo);
                return experimentProcessSampleNgsOrSangerVo;
            }).collect(Collectors.toList()));
        }
        return ngsHszbqVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByNgsId(Long ngsId) {
        mapper.deleteByNgsId(ngsId);
    }

    @Override
    public Long insert(NgsHszbq ngsHszbq) {
        Date now = new Date();
        ngsHszbq.setCreateTime(now);
        ngsHszbq.setUpdateTime(now);
        if (Objects.isNull(ngsHszbq.getSystmqj())) {
            ngsHszbq.setSystmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getZlxbblsffh())) {
            ngsHszbq.setZlxbblsffh(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getCddnandycd())) {
            ngsHszbq.setCddnandycd(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getTzdnand())) {
            ngsHszbq.setTzdnand(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getZpcrgzjrfrag())) {
            ngsHszbq.setZpcrgzjrfrag(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getGsgg())) {
            ngsHszbq.setGsgg(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getGcywyc())) {
            ngsHszbq.setGcywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getQjjzwxzssygztm())) {
            ngsHszbq.setQjjzwxzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getQjyyq())) {
            ngsHszbq.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getQjlxj())) {
            ngsHszbq.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getClsyfqw())) {
            ngsHszbq.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getLxj())) {
            ngsHszbq.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getZdq())) {
            ngsHszbq.setZdq(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(ngsHszbq.getAqgt())) {
            ngsHszbq.setAqgt(StatusEnum.NORMAL.getCode().byteValue());
        }
        return mapper.insert(ngsHszbq) > 0 ? ngsHszbq.getId() : 0L;
    }

    @Override
    public boolean update(NgsHszbq ngsHszbq) {
        Date now = new Date();
        ngsHszbq.setUpdateTime(now);
        return mapper.updateByPrimaryKey(ngsHszbq) != 0;
    }

    @Override
    public Integer count(NgsHszbqSearchVo ngsHszbqSearchVo) {
        return mapper.count(ngsHszbqSearchVo);
    }

    @Override
    public List<NgsHszbqVo> selectList(NgsHszbqSearchVo ngsHszbqSearchVo) {
        return mapper.selectList(ngsHszbqSearchVo);
    }

    @Override
    public Page<NgsHszbqVo> selectPage(NgsHszbqSearchVo ngsHszbqSearchVo) {
        //先直接查总数
        int count = count(ngsHszbqSearchVo);
        //分页
        Page<NgsHszbqVo> page = new Page<>(true, count, ngsHszbqSearchVo.getPageNum(), ngsHszbqSearchVo.getPageSize());
        ngsHszbqSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<NgsHszbqVo> responseVos = this.selectList(ngsHszbqSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(NgsHszbqSaveOrUpdateVo ngsHszbqSaveOrUpdateVo) {
        Long ngsId = ngsHszbqSaveOrUpdateVo.getNgsId();
        Ngs ngs = ngsService.selectById(ngsId);
        AssertUtil.notNull(ngs, "此实验不存在或者已被删除");
        if (ngs.getStatus() < NgsStatusEnum.WKZBQ1.getCode().byteValue()) {
            //修改实验的状态
            ngsService.updateByPrimaryKeySelective(Ngs.builder()
                    .id(ngsId)
                    .status(NgsStatusEnum.WKZBQ1.getCode().byteValue())
                    .build());
        }
        List<SangerSjpzqPcrDto> pdhfyybDataList = ngsHszbqSaveOrUpdateVo.getPdhfyybDataList();
        if (CollectionUtil.isNotEmpty(pdhfyybDataList)) {
            ngsHszbqSaveOrUpdateVo.setPdhfyybData(JsonUtil.toString(pdhfyybDataList));
        }
        NgsHszbq dbParam = new NgsHszbq();
        BeanUtils.copyProperties(ngsHszbqSaveOrUpdateVo, dbParam);
        NgsHszbq oldNgsHszbq = this.selectByNgsId(ngsId);
        if (Objects.isNull(oldNgsHszbq)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldNgsHszbq.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleUpdateVo> ngsReadyList = ngsHszbqSaveOrUpdateVo.getNgsReadyList();
        if (CollectionUtil.isEmpty(ngsReadyList)) {
            return false;
        }
        ngsReadyList.forEach(e -> {
            ExperimentProcessSample updateParam = new ExperimentProcessSample();
            BeanUtil.copyProperties(e, updateParam, "moleculePathologyNumber", "project");
            experimentProcessSampleService.updateByPrimaryKeySelective(updateParam);
        });
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .experimentProcessId(ngsId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(ngsId)
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .op(String.format("%s%s-%s", ngs.getName(), ngs.getProcessNumber(), NgsStatusEnum.HSZBQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}